package com.ta.gulimall.order.controller;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import com.ta.gulimall.common.utils.RedisUtil;
import com.ta.gulimall.order.constant.OrderConstant;
import com.ta.gulimall.order.view.vo.OrderConfirmVo;
import com.ta.gulimall.order.view.vo.OrderSubmitVo;
import com.ta.gulimall.order.view.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import com.ta.gulimall.order.view.entity.OrderEntity;
import com.ta.gulimall.order.service.OrderService;
import com.ta.gulimall.common.utils.system.PageUtils;
import com.ta.gulimall.common.utils.system.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 订单
 *
 * @author tuao
 * @email tuaoo@gmail.com
 * @date 2022-10-29 01:15:27
 */
@RestController
@RequestMapping("order/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 商品结算
     * @return
     */
    @GetMapping("/confirm")
    public R goodsConfirm(HttpServletRequest request) throws ExecutionException, InterruptedException {
        OrderConfirmVo vo = orderService.goodsConfirm();
        return R.ok(vo);
    }

    /**
     * 创建订单
     * @param vo
     * @return
     */
    @PostMapping("/submitOrder")
    public R submitOrder(OrderSubmitVo vo){
        long result = redisUtil.sSetAndTime(OrderConstant.ORDER_SUBMIT_IDEMPOTENT_KEY, 60 * 10, vo.getOrderToken());
        if(result != 1){
            throw new RuntimeException("重复提交!");
        }

        SubmitOrderResponseVo responseVo = orderService.submitOrder(vo);
        return R.ok(responseVo);
    }




    //================以下是系统代码=================
    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = orderService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		OrderEntity order = orderService.getById(id);

        return R.ok().put("order", order);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody OrderEntity order){
		orderService.save(order);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody OrderEntity order){
		orderService.updateById(order);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		orderService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
